<template>
  <div :class="getWrapperClass">
    <div class="comment-input-placeholder" v-if="!commentActive" @click="showCommentInput">请输入</div>
    <div v-if="commentActive">
      <el-input v-model="dataForm.text" type="textarea" :rows="4"
        class="comment-input-wrapper-content" placeholder="请输入" maxlength="500" show-word-limit
        ref="textRef" @input="handleContentChange" />
      <template v-if="dataForm.image.length">
        <div class="comment-img-list">
          <div class="img-item" v-for="(item, i) in dataForm.image" :key="i">
            <el-image :src="define.comUrl + item.url" class="img-item"
              :preview-src-list="getImgList(dataForm.image)" :z-index="100">
            </el-image>
            <div class="badge" @click.stop="handleImgRemove(i)">
              <i class="icon-ym icon-ym-nav-close"></i>
            </div>
          </div>
        </div>
      </template>
      <jnpf-upload-file ref="uploadFileRef" v-model="dataForm.file" :limit="9" detailed
        class="comment-upload-file" />
      <div class="comment-input-wrapper-actions">
        <div class="actions-left">
          <el-tooltip content="选择@用户">
            <i class="icon-ym icon-ym-roll-call" @click="openSelectUser()"></i>
          </el-tooltip>
          <el-tooltip content="上传图片" v-if="dataForm.image && dataForm.image.length >= 9">
            <i class="icon-ym icon-ym-comment-img" @click="imageCountOver()"></i>
          </el-tooltip>
          <el-upload v-else accept="image/*" :show-file-list="false" multiple
            :action="define.comUploadUrl + '/annexpic'" :headers="getHeaders"
            :before-upload="beforeImgUpload" :on-success="handleImgSuccess" ref="elUploadImg"
            class="upload-btn">
            <el-tooltip content="上传图片">
              <i class="icon-ym icon-ym-comment-img"></i>
            </el-tooltip>
          </el-upload>
          <el-tooltip content="上传附件">
            <i class="icon-ym icon-ym-comment-file" @click="uploadFile"></i>
          </el-tooltip>
          <el-tooltip content="表情">
            <i class="icon-ym icon-ym-emoji" v-popover:popover></i>
          </el-tooltip>
          <el-popover placement="top" trigger="click" popper-class="emoji-popover"
            v-model="popoverVisible" ref="popover">
            <template>
              <div class="emojiBox">
                <ul class="emoji">
                  <li v-for="(item, i) in this.emojiList" :key="i" @click="handleSelectEmoji(item)">
                    <img :src="item.url | urlFilter()" />
                  </li>
                </ul>
              </div>
            </template>
          </el-popover>
        </div>
        <div>
          <el-button @click="hideCommentInput" class="mr-10px">取消</el-button>
          <el-button type="primary" @click="sendComment" :disabled="getSubmitDisabled"
            :loading="btnLoading">发送</el-button>
        </div>
      </div>
    </div>
    <FlowUserModal :taskId="taskId" :selectType="'custom'" multiple ref="flowUserModal"
      @confirm="handleSelectUser" />
    <Preview :visible.sync="previewVisible" :file="activeFile" :showDownload="true" />
  </div>
</template>

<script>

import emojiList from 'static/emoji.json';
import { createComment } from '@/api/workFlow/FlowEngine'
import Preview from '@/components/Jnpf/Upload/Preview.vue'
import FileUploader from '@/views/workFlow/components/FileUploader.vue'
import FlowUserModal from '@/views/workFlow/CommentExtra/modal/FlowUserModal.vue'

export default {
  name: 'CommentInput',
  components: { FileUploader, Preview, FlowUserModal },
  filters: {
    urlFilter(url) {
      return require(`static/emoji/${url}`)
    }
  },
  props: {
    taskId: {
      type: String,
      default: ''
    },
    replyId: {
      type: String,
      default: ''
    },
    inner: {
      type: Boolean,
      default: false
    },
    index: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      commentActive: false,
      imgList: [],
      emojiList: emojiList,
      popoverVisible: false,
      imgUploading: false,
      dataForm: {
        text: '',
        file: [],
        image: [],
      },
      selectionStart: 0,
      selectForm: '',
      btnLoading: false,
      apiUrl: '',
      previewVisible: false,
      activeFile: {},
      fileAccept: '.xls,.xlsx,.doc,.docx,.pdf,.txt,.ppt,.pptx'
    }
  },
  computed: {
    getWrapperClass() {
      return [
        'comment-input-wrapper',
        {
          'comment-input-wrapper-inner': this.inner,
          'comment-input-wrapper-active': this.commentActive,
        },
      ];
    },
    getHeaders() {
      return { Authorization: this.$store.getters.token };
    },
    getSubmitDisabled() {
      return !this.dataForm.text
    },
  },
  methods: {
    showCommentInput() {
      this.commentActive = true;
      this.$nextTick(() => {
        this.$refs.textRef.focus()
      });
    },
    hideCommentInput() {
      this.commentActive = false;
      this.clearAll();
      if (this.inner) {
        this.$emit('hideCommentInput', this.index)
      }
    },
    clearAll() {
      this.btnLoading = false;
      this.dataForm.text = '';
      this.imgList = [];
      this.dataForm.image = [];
      this.dataForm.file = [];
    },
    sendComment() {
      this.btnLoading = true;
      let query = {
        text: this.dataForm.text,
        file: JSON.stringify(this.dataForm.file),
        image: JSON.stringify(this.dataForm.image),
        taskId: this.taskId,
        replyId: this.replyId,
      };
      createComment(query).then(() => {
        this.btnLoading = false;
        this.clearAll();
        this.$emit('reload')
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    handleContentChange(value) {
      if (!value || !value.endsWith("@")) {
        return;
      }
      this.selectForm = 'input';
      this.selectionStart = value.length;
      this.$refs.flowUserModal.openDialog();
    },
    openSelectUser() {
      this.selectForm = 'btn';
      this.selectionStart = -1;
      this.$refs.flowUserModal.openDialog();
    },
    handleSelectUser(data) {
      if (!data || !data.length) return;
      let addContent = this.selectForm === 'btn' ? '@' : '';
      for (let i = 0; i < data.length; i++) {
        let str = (i > 0 ? '@' : '') + `{${data[i].fullName}}`;
        addContent += str;
      }
      if (this.selectionStart === -1) {
        this.dataForm.text += addContent;
        this.$refs.textRef.focus();
      } else {
        let oldValue = this.dataForm.text;
        let rangeIndex = this.selectionStart + addContent.length;
        this.dataForm.text = oldValue.slice(0, this.selectionStart) + addContent + oldValue.slice(this.selectionStart);
        setTimeout(() => {
          this.$refs.textRef.focus()
          // textRef.value?.resizableTextArea?.textArea?.setSelectionRange(rangeIndex, rangeIndex);
        }, 50);
      }
    },
    handleSelectEmoji(item) {
      this.dataForm.text += item.alt;
      this.popoverVisible = false;
      this.$refs.textRef.focus();
    },
    imageCountOver() {
      this.$message({ message: '最多可以上传9张图片', type: 'error', duration: 1000 })
      return false;
    },
    beforeImgUpload(file) {
      if (this.dataForm.image.length >= 9) {
        this.$message({ message: '最多可以上传9张图片', type: 'error', duration: 1000 })
        return false;
      }
      if (file.size > 10 * 1024 * 1024) {
        this.$message({ message: '图片大小超过10MB', type: 'error', duration: 1000 })
        return false;
      }
      let isAccept = new RegExp('image/*').test(file.type);
      if (!isAccept) {
        this.$message({ message: '请上传图片', type: 'error', duration: 1000 })
        return false;
      }
    },
    handleImgSuccess(res, file, fileList) {
      if (res.code == 200) {
        if (this.dataForm.image.length >= 9) {
          this.$message({ message: '最多可以上传9张图片', type: 'error', duration: 1000 })
        } else {
          this.dataForm.image.push({
            name: file.name,
            fileId: res.data.name,
            url: res.data.url,
            thumbUrl: res.data.thumbUrl,
          })
        }
      } else {
        this.$refs.elUploadImg.uploadFiles.splice(fileList.length - 1, 1)
        fileList.filter(o => o.uid != file.uid)
        this.$message({ message: res.msg, type: 'error', duration: 1500 })
      }
      this.imgUploading = false
    },
    handleChange({ file }) {
      if (file.status === 'uploading') return (this.imgUploading = true);
      if (file.status === 'error') {
        this.imgUploading = false;
        this.imgList = this.imgList.filter(o => o.uid != file.uid);
        this.$message({ message: '上传失败', type: 'error', duration: 1000 })
        return;
      }
      if (file.status === 'done') {
        this.imgUploading = false;
        if (file.response.code === 200) {
          const isTopLimit = this.dataForm.image.length >= 9;
          if (isTopLimit) {
            this.$message({ message: '最多可以上传9张图片', type: 'error', duration: 1000 })
            return false;
          }
          this.dataForm.image.push({
            name: file.name,
            fileId: file.response.data.name,
            url: file.response.data.url,
          });
        } else {
          this.imgList = this.imgList.filter(o => o.uid != file.uid);
          this.$message({ message: file.response.msg, type: 'error', duration: 1000 })
        }
      }
    },
    getImgList(list) {
      const newList = list.map(o => this.define.comUrl + o.url)
      return newList
    },
    handleImgRemove(index) {
      this.dataForm.image.splice(index, 1);
      this.imgList.splice(index, 1);
    },
    handlePreview(row) {
      this.activeFile.name = row.fullName;
      this.activeFile.fileId = row.filePath;
      this.activeFile.fileVersionId = null;
      this.activeFile.url = row.url;
      this.previewVisible = true;
    },
    uploadFile() {
      if (this.dataForm.file.length >= 9) {
        this.$message({ message: '最多可以上传9个文件', type: 'error', duration: 1000 })
        return
      }
      this.$refs.uploadFileRef && this.$refs.uploadFileRef.uploadFile()
    }
  }
}
</script>

<style lang="scss" scoped>
.comment-input-wrapper {
  &.comment-input-wrapper-inner {
    margin-top: 5px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    &.comment-input-wrapper-active {
      border: 1px solid #1890ff;
    }
    .comment-input-placeholder {
      color: #bfbfbf;
      line-height: 30px;
      height: 96px;
      padding: 0 11px;
    }
  }
  .comment-input-placeholder {
    color: #bfbfbf;
    line-height: 50px;
    padding: 0 10px;
  }
  ::v-deep .comment-input-wrapper-content {
    margin-bottom: 0px;
    textarea {
      border: 0px;
      box-shadow: unset !important;
    }
  }
  .ant-input-textarea-show-count::after {
    padding-right: 10px;
  }
  .comment-input-wrapper-actions {
    padding: 0 10px;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .actions-left {
      display: flex;
      align-items: center;
      .ym-custom,
      .icon-ym {
        font-size: 18px;
        margin-right: 15px;
        color: #bfbfbf;
        cursor: pointer;
      }
    }
  }
  .comment-img-list {
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    padding-left: 10px;
    .img-item {
      width: 40px;
      height: 40px;
      position: relative;
      margin-right: 10px;
      cursor: pointer;
      object-fit: cover;
      flex-shrink: 0;
      margin-bottom: 10px;

      .badge {
        background-color: red;
        border-radius: 10px;
        color: #fff;
        font-size: 12px;
        height: 18px;
        width: 18px;
        line-height: 18px;
        border: 1px solid #fff;
        position: absolute;
        right: -9px;
        top: -9px;
        cursor: pointer;
        z-index: 100;
        display: flex;
        justify-content: center;
        align-items: center;
        .icon-ym {
          font-size: 12px;
          transform: scale(0.7);
          display: inline-block;
        }
      }
    }
  }
  .comment-upload-file {
    padding: 0 10px;
    .anticon-close {
      display: block !important;
    }
    .upload-file-list__item {
      margin-top: 5px !important;
    }
  }
}

.emojiBox {
  height: 150px;
  width: 300px;
  overflow: auto;
  text-align: left;
}
.emojiBox .emoji {
  padding: 0;
}
.emojiBox li {
  display: inline-block;
  width: 28px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  cursor: pointer;
}
.emoji-popover {
  z-index: 30000 !important;
  .ant-popover-inner-content {
    padding: 10px;
  }
}
</style>
